<script setup>
import { useRouter } from 'vue-router';
import { ref, computed } from 'vue';
import { loginFn } from '@/api/login';
import { useUserStore } from '@/stores/user';
import { showToast } from 'vant';

const user = useUserStore()
const tel = ref('')
const password = ref('123123')
const router = useRouter()

if (user.userInfo.userid) {
    router.push('/home')
}

function tohome() {
    router.push('/home')
}

function onSubmit() {
    loginFn({
        tel: tel.value,
        password: password.value
    }).then(res => {
        // console.log(res);

        showToast(res.message)
        if (res.data.flag) {
            router.push('/home')
        } else if (!res.data.exits) {
            router.push('/register')
        } else {
            password.value = ''
        }
    })
}

const flag = computed(() => {
    return !(/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(tel.value) && password.value.length >= 6)
})
</script>

<template>
    <div class="main">
        <van-nav-bar title="登录" left-text="返回首页" left-arrow @click-left="tohome" />
        <div class="content">
            <van-form @submit="onSubmit">
                <van-cell-group inset>
                    <van-field v-model="tel" name="手机号" label="手机号" placeholder="手机号"
                        :rules="[{ required: true, message: '请填写手机号' }]" />
                    <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
                        :rules="[{ required: true, message: '请填写密码' }]" />
                </van-cell-group>
                <div style="margin: 16px;">
                    <van-button round block type="danger" native-type="submit" :disabled="flag">
                        登录
                    </van-button>
                </div>
            </van-form>
            <div style="margin: 16px;">
                <van-button @click="$router.push('/register')" round block type="primary" native-type="submit">
                    注册
                </van-button>
            </div>
        </div>
    </div>
</template>
<style lang="scss" scoped></style>